//
//  NearbyViewController.m
//  Zhai
//
//  Created by 周文静 on 16/7/28.
//  Copyright © 2016年 lechuangshidai. All rights reserved.
//

#import <CoreLocation/CoreLocation.h>

#import "NearbyViewController.h"
#import "NearbyCell.h"
#import "PhoneSelfRoomViewController.h"
#import "AFManager.h"
#import "UIImageView+WebCache.h"
@interface NearbyViewController ()<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate>
{
    NSMutableArray *dataArr;
}
@property (weak, nonatomic) IBOutlet UITableView *nearbyTable;

@property (strong,nonatomic) CLLocationManager *locationManager;
@end

@implementation NearbyViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 删除系统自带的tabBarButton
    for (UIView *tabBarButton in self.tabBarController.tabBar.subviews) {
        
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            
            [tabBarButton removeFromSuperview];
        }
    }
    
    //判断的手机的定位功能是否开启
    //开启定位:设置 > 隐私 > 位置 > 定位服务
    if([CLLocationManager
        locationServicesEnabled]) {
        //启动位置更新
        //开启位置更新需要与服务器进行轮询所以会比较耗电，在不需要时用stopUpdatingLocation方法关闭;
        [self.locationManager startUpdatingLocation];
        
        NSLog(@"定位已开启");


    }
    else{
        [NSObject wj_alterSingleVCWithOneTitle:@"无法获取你的位置信息" andTwoTitle:@"请到手机系统的[设置]->[隐私]->[定位服务]中打开定位服务,并允许宅使用定位服务" andSelfVC:self];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"附近的人";
    dataArr = [[NSMutableArray alloc]init];

    //1. 创建CLLocationManager对象
    _locationManager = [CLLocationManager new];
    
    //2.当用户使用的使用授权 --> 能看见APP界面的时候就是使用期间
    if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        
        [_locationManager requestWhenInUseAuthorization];
    }
    
    //3. 设置代理 --> 获取用户位置
    _locationManager.delegate = self;
    
    //4.设置定位精度
    _locationManager.desiredAccuracy= kCLLocationAccuracyBest;
    
    //5.至少移动10再通知委托处理更新
     _locationManager.distanceFilter= 10.0f;
    
    //6. 调用开始定位方法
    [_locationManager startUpdatingLocation];
    
    [self setExtraCellLineHidden:_nearbyTable];
    [AFManager getReqURL:[NSString stringWithFormat:@"%@?uid=%@&page=%@&num=%@",SHOUYE,@"11",@"0",@"15"] block:^(id infor) {
        NSLog(@"--%@",infor);
        [dataArr addObjectsFromArray:infor[@"data"]];
        [self.nearbyTable reloadData];
    } errorblock:^(NSError *error) {
        NSLog(@"--%@--",error);
    }];
}






#pragma mark 代理方法
/** 当完成位置更新的时候调用 --> 次方法会频繁调用*/
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = locations.lastObject;
    NSLog(@"latitude: %f, longitude: %f",location.coordinate.latitude, location.coordinate.longitude);
    [AFManager postReqURL:JINGWEIDU reqBody:@{@"id":[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"],@"lat":[NSString stringWithFormat:@"%f",location.coordinate.latitude],@"pre":[NSString stringWithFormat:@"%f",location.coordinate.longitude]} block:^(id infor) {
        NSLog(@"infor====%@",infor);
        if ([[NSString stringWithFormat:@"%@",infor[@"code"]] isEqualToString:@"200"]) {
           
            
        }
    }];
    //停止位置更新
    [manager stopUpdatingLocation];
}


#pragma mark   ===========  定位失败时调用  ===========
- (void)locationManager: (CLLocationManager *)manager
       didFailWithError: (NSError *)error {
    
    NSString *errorString;
    [manager stopUpdatingLocation];
    //    NSLog(@"Error: %@",[error localizedDescription]);
    switch([error code]) {
        case kCLErrorDenied:
            //访问用户拒绝的位置服务
            errorString = @"Access to Location Services denied by user";
            break;
        case kCLErrorLocationUnknown:
            //位置数据不可用
            errorString = @"Location data unavailable";
            break;
        default:
            //发生了一个未知的错误
            errorString = @"An unknown error has occurred";
            break;
    }
    
    [NSObject wj_alterSingleVCWithOneTitle:@"无法获取你的位置信息" andTwoTitle:@"请到手机系统的[设置]->[宅]->[位置]中设置允许宅访问位置信息" andSelfVC:self];
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NearbyCell *cell = [NearbyCell nearbyViewCellWithTableView:tableView];
    cell.nameLabel.text = dataArr[indexPath.row][@"nickname"];
    cell.ageLabel.text =[NSString stringWithFormat:@"%@岁",dataArr[indexPath.row][@"birthday"]];
    if ([[NSString stringWithFormat:@"%@",dataArr[indexPath.row][@"auto"]] length]>0) {
        cell.declarationLabel.text = dataArr[indexPath.row][@"auto"];
        
    }else{
        cell.declarationLabel.text = @"太懒了，还没有宣言。";
        
        
    }
    if ([[NSString stringWithFormat:@"%@",dataArr[indexPath.row][@"sex"]] isEqualToString:@"0"]) {
//        cell.homeSexLabel.text = @"男";
    }else if ([[NSString stringWithFormat:@"%@",dataArr[indexPath.row][@"sex"]] isEqualToString:@"1"]){
//        cell.homeSexLabel.text = @"女";
    }else{
//        cell.homeSexLabel.text = [NSString stringWithFormat:@"%@",dataArr[indexPath.row][@"sex"]];
//        cell.homeSexLabel.text = @"未知";
    }
    
    [cell.iconImage setImageWithURL:[NSURL URLWithString:dataArr[indexPath.row][@"head_pic"]] placeholderImage:[UIImage imageNamed:@"fx-tx5"]];
    cell.iconImage.layer.masksToBounds = YES;
    cell.iconImage.layer.cornerRadius = 35;
    [cell nearbyPhoneBtnAct:^{
        
        NSLog(@"点击了 %ld 打电话",(long)indexPath.row);
    }];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PhoneSelfRoomViewController *phoneSelfRoomVC = [[PhoneSelfRoomViewController alloc]initWithNibName:@"PhoneSelfRoomViewController" bundle:nil];
    [self.navigationController pushViewController:phoneSelfRoomVC animated:YES];
}

//隐藏table多余的线
- (void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view =[ [UIView alloc]init];
    
    view.backgroundColor = [UIColor whiteColor];
    
    [tableView setTableFooterView:view];
    
    [tableView setTableHeaderView:view];
    
}


@end
